package com.pcbly.web.persistence.depart;

import java.util.List;

import com.pcbly.web.bean.system.DepartBean;
import com.pcbly.web.bean.system.DepartChildBean;
import com.pcbly.web.components.utils.random.GUID;
import com.pcbly.web.persistence.HibernateBaseDao;

@SuppressWarnings("unchecked")
public class DepartHibernateDao extends HibernateBaseDao<DepartBean> implements
		DepartDao {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7187871280314003413L;

	public DepartHibernateDao() {
		super();
	}

	protected Class<DepartBean> getEntityClass() {
		return DepartBean.class;
	}

	@Override
	public void saveDepartBean(DepartBean bean) throws Exception {
		// TODO Auto-generated method stub
		String id = (new GUID()).toString();
		bean.setId(id);
		if (logger.isDebugEnabled()) {
			logger.debug(bean.getId());
			logger.debug(bean.getCreateUserId());
			logger.debug(bean.getDepartDescn());
			logger.debug(bean.getParent());
		}
		getSession().save(bean);
	}

	@Override
	public List<DepartChildBean> findDepartChildBeansByParentId(String parentId)
			throws Exception {
		// TODO Auto-generated method stub
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT a.ID,a.DEPARTNAME,COUNT(b.ID) CHILD_ ");
		sql.append(" FROM sys_depart a LEFT JOIN sys_depart b ");
		sql.append("ON a.ID=b.PARENTID  where a.PARENTID=? ");
		sql.append(" GROUP BY a.ID,a.DEPARTNAME");

		return getSession().createSQLQuery(sql.toString()).addEntity(
				DepartChildBean.class).setString(0, parentId).list();
	}

	@Override
	public List<DepartBean> findDepartBeansByParentId(String parentId)
			throws Exception {
		// TODO Auto-generated method stub
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT * ");
		sql.append(" FROM sys_depart ");
		sql.append(" where PARENTID=? ");
		return getSession().createSQLQuery(sql.toString()).addEntity(
				DepartBean.class).setString(0, parentId).list();
	}

}
